package com.sunnada.edu.business.project.service;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.sunnada.edu.business.project.dao.ProjectDao;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.pub.util.Utils;

@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {
	private static final Logger logger = LoggerFactory
			.getLogger(ProjectServiceImpl.class);
	@Resource
	ProjectDao projectDao;

	@Override
	public int getProjectCots(HashMap<String, String> params) {
		return projectDao.getProjectCots(params);
	}

	@Override
	public List<?> findProjects(HashMap<String, String> params) {
		return projectDao.findProjects(params);
	}

	@Override
	public String projectDelete(HashMap<String, String> params) {
		String msg = "";
		int num = projectDao.projectDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String projectAdd(HashMap<String, String> params,
			HttpServletRequest request) {
		String msg = "";
		int cot = ProjectMethods.getProjectByName(params);
		if (cot > 0) {
			msg = "2";// 项目名称已存在，请更换！
		} else {
			String recId = UUID.randomUUID().toString();
			params.put("recId", recId);
			int num = projectDao.projectAdd(params);// 添加工程信息
			if (num == 0) {
				msg = "0";// 失败
			} else {
				// 创建一个通用的多部分解析器
				CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				// 判断 request 是否有文件上传,即多部分请求
				if (multipartResolver.isMultipart(request)) {
					// 转换成多部分request
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					// 取得request中的所有文件名
					List<MultipartFile> filelist = multiRequest
							.getFiles("contract");// 图片列表
					for (int i = 0; i < filelist.size(); i++) {
						MultipartFile file = filelist.get(i);
						String fileName = file.getOriginalFilename();// 原文件名
						String fileType = file.getContentType();// 原文件类型
						String name = file.getName();// form表单字段name属性值
						// 存文件
						String savePath = FileSave(file, request);
						params.put("path", savePath);
						params.put("fileName", fileName);
						params.put("owner", recId);
						ProjectMethods.contractAdd(params);// 添加工程合同
					}

				}
				msg = "1";// 成功
			}
		}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String projectUpdate(HashMap<String, String> params,
			HttpServletRequest request) {
		String msg = "";
		int cot = ProjectMethods.getProjectByName(params);
		if (cot > 1) {
			msg = "2";// 班组名称已存在，请更换！
		} else {
			int num = projectDao.projectUpdate(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				
				// 创建一个通用的多部分解析器
				CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				// 判断 request 是否有文件上传,即多部分请求
				if (multipartResolver.isMultipart(request)) {
					// 转换成多部分request
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					// 取得request中的所有文件名
					List<MultipartFile> filelist = multiRequest
							.getFiles("contract");// 图片列表
					for (int i = 0; i < filelist.size(); i++) {
						MultipartFile file = filelist.get(i);
						String fileName = file.getOriginalFilename();// 原文件名
						String fileType = file.getContentType();// 原文件类型
						String name = file.getName();// form表单字段name属性值
						// 存文件
						String savePath = FileSave(file, request);
						params.put("path", savePath);
						params.put("fileName", fileName);
						params.put("owner", params.get("recId"));
						ProjectMethods.contractAdd(params);// 添加工程合同
					}

				}
				
				msg = "1";// 成功
			}
		}
		return msg;
	}

	@Override
	public Map getProjectByRecId(HashMap<String, String> params) {
		return projectDao.getProjectByRecId(params);
	}

	@Override
	public Map<String, String> getProject(HashMap<String, String> params) {
		return projectDao.getProject(params);
	}

	@Override
	public String projectEnable(HashMap<String, String> params) {
		String msg = "";
		int num = projectDao.projectEnable(params);
		if (num == 0) {
			msg = "启用失败！";
		}
		return msg;
	}

	@Override
	public String projectDisable(HashMap<String, String> params) {
		String msg = "";
		int num = projectDao.projectDisable(params);
		if (num == 0) {
			msg = "停用失败！";
		}
		return msg;
	}

	public String FileSave(MultipartFile file, HttpServletRequest request) {
		if (Utils.isNull(file)) {
			return "";
		}
		// 实际名称
		String fileName = file.getOriginalFilename();
		// 保存附件
		if (Utils.isNotNull(fileName)) {
			// 物理根目录
			String rootPath = request.getSession().getServletContext()
					.getRealPath("/");
			// 相对路径
			String filePath = "upload/contract/"
					+ DateUtil.simpleDateFormat("yyyyMM").format(new Date());
			// 保存文件路径
			String savePath = filePath
					+ "/"
					+ DateUtil.simpleDateFormat("yyyyMMddHHmmssSSS").format(
							new Date())
					+ fileName.substring(fileName.lastIndexOf("."),
							fileName.length());

			if (!new File(rootPath + filePath).exists()) {
				new File(rootPath + filePath).mkdirs();
			}

			try {
				file.transferTo(new File(rootPath + savePath));
				return savePath;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return "";
	}

}
